import type { Router } from "vue-router";
import nprogress from "nprogress";
import "nprogress/nprogress.css";
import { isLogin } from "@/utils/auth";
import { auth as useAuth, user as useUser } from "@/store";
import { globalUserId, zuulToken } from "@/utils/constants.ts";
import Cookies from "js-cookie";

const nologin = ["/login", "/replace"];

nprogress.configure({
  // 动画方式
  easing: "ease",
  // 递增进度条的速度
  speed: 500,
  // 是否显示加载ico
  showSpinner: false,
  // 自动递增间隔
  trickleSpeed: 200,
  // 初始化时的最小百分比
  minimum: 0.3
});

export default (router: Router) => {
  router.beforeEach((to: any, from: any, next: any) => {
    nprogress.start();
    // Cookies.set(globalUserId, 'f9080dfa8a734d3e87167bc04aae4e73');
    // Cookies.set(zuulToken, 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJhdXRoMCIsImV4cCI6MTcxMDQ2OTE2NSwiZGV2aWNlSWQiOiIiLCJ1c2VySWQiOiJmOTA4MGRmYThhNzM0ZDNlODcxNjdiYzA0YWFlNGU3MyIsInRpbWVvdXQiOjI0fQ.O-RME3r1qwVNdZdgCn-FQ3835Za0ICyf2kFS6eUUehA');

    if (nologin.some(v => (to.fullPath.includes(v)))) {
      next();
    } else {
      if (isLogin()) {
        const auth = useAuth();
        const user = useUser();
        if (auth.routes.length > 0) {
          next();
        } else {
          auth.SET_MENU_ROUTE().then(async (res: boolean) => {
            if (!user.$state.userName) {
              await user.setUser();
            }
            if (res) {
              next(to.path); // hack方法 确保addRoutes已完成
            } else {
              next("/");
            }
          });
        }
      } else {
        next({ path: '/replace', replace: true });
      }
    }
  })

  router.afterEach((to: any, _from: any) => {
    document.title = `登记证管理平台 - ${to.meta.title}`;
    nprogress.done();
  });
}